// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const artPostsCollection = db.collection('artPosts')
const commentsCollection = db.collection('artComments')
const likesCollection = db.collection('artLikes')

// 云函数入口函数
exports.main = async (event, context) => {
  console.log('createArtPosts 云函数被调用，参数:', event);
  
  try {
    const wxContext = cloud.getWXContext()
    const openid = wxContext.OPENID
    const { action, data } = event
    
    console.log('云函数参数解析:', { openid, action, data });
    
    if (!openid) {
      return {
        success: false,
        message: '用户未登录',
        error: 'openid获取失败'
      }
    }
    
    if (!action) {
      return {
        success: false,
        message: '缺少操作类型',
        error: 'action参数缺失'
      }
    }
    
    switch (action) {
      case 'create':
        return await createPost(openid, data)
      case 'getPosts':
        return await getPosts(data)
      case 'like':
        return await toggleLike(openid, data)
      case 'comment':
        return await addComment(openid, data)
      case 'getComments':
        return await getComments(data)
      case 'delete':
        return await deletePost(openid, data)
      default:
        return {
          success: false,
          message: '未知操作',
          error: `不支持的操作类型: ${action}`
        }
    }
  } catch (error) {
    console.error('createArtPosts 错误:', error)
    console.error('错误详情:', {
      message: error.message,
      stack: error.stack,
      name: error.name
    })
    return {
      success: false,
      message: '操作失败',
      error: error.message || error
    }
  }
}

// 创建帖子
async function createPost(openid, data) {
  console.log('开始创建帖子，参数:', { openid, data });
  
  const { content, images, video, userInfo } = data
  
  console.log('解析数据:', {
    content: content,
    imagesCount: images?.length || 0,
    hasVideo: !!video,
    userInfo: userInfo
  });
  
  if (!content && (!images || images.length === 0) && !video) {
    console.log('内容验证失败：所有内容都为空');
    return {
      success: false,
      message: '内容不能为空'
    }
  }
  
  try {
    const postData = {
      openid,
      content: content || '',
      images: images || [],
      video: video || null,
      userInfo: userInfo || {},
      createTime: new Date(),
      updateTime: new Date(),
      likeCount: 0,
      commentCount: 0,
      isLiked: false
    }
    
    console.log('准备插入数据库的数据:', postData);
    
    const result = await artPostsCollection.add({
      data: postData
    })
    
    console.log('数据库插入成功，结果:', result);
    
    return {
      success: true,
      message: '发布成功',
      postId: result._id
    }
  } catch (error) {
    console.error('创建帖子失败:', error);
    console.error('错误详情:', {
      message: error.message,
      stack: error.stack,
      name: error.name,
      errCode: error.errCode
    });
    
    return {
      success: false,
      message: '发布失败',
      error: error.message || error
    }
  }
}

// 获取帖子列表
async function getPosts(data) {
  const { page = 1, pageSize = 10 } = data
  const skip = (page - 1) * pageSize
  
  const posts = await artPostsCollection
    .orderBy('createTime', 'desc')
    .skip(skip)
    .limit(pageSize)
    .get()
  
  // 获取用户信息
  const postsWithUserInfo = await Promise.all(
    posts.data.map(async (post) => {
      // 获取点赞状态
      const likeRecord = await likesCollection.where({
        postId: post._id,
        openid: post.openid
      }).get()
      
      return {
        ...post,
        isLiked: likeRecord.data.length > 0
      }
    })
  )
  
  return {
    success: true,
    data: postsWithUserInfo,
    hasMore: postsWithUserInfo.length === pageSize
  }
}

// 点赞/取消点赞
async function toggleLike(openid, data) {
  const { postId } = data
  
  const likeRecord = await likesCollection.where({
    postId,
    openid
  }).get()
  
  if (likeRecord.data.length > 0) {
    // 取消点赞
    await likesCollection.where({
      postId,
      openid
    }).remove()
    
    await artPostsCollection.doc(postId).update({
      data: {
        likeCount: db.command.inc(-1)
      }
    })
    
    return {
      success: true,
      message: '取消点赞成功',
      isLiked: false
    }
  } else {
    // 添加点赞
    await likesCollection.add({
      data: {
        postId,
        openid,
        createTime: new Date()
      }
    })
    
    await artPostsCollection.doc(postId).update({
      data: {
        likeCount: db.command.inc(1)
      }
    })
    
    return {
      success: true,
      message: '点赞成功',
      isLiked: true
    }
  }
}

// 添加评论
async function addComment(openid, data) {
  const { postId, content, userInfo } = data
  
  if (!content.trim()) {
    return {
      success: false,
      message: '评论内容不能为空'
    }
  }
  
  const commentData = {
    postId,
    openid,
    content: content.trim(),
    userInfo: userInfo || {},
    createTime: new Date()
  }
  
  await commentsCollection.add({
    data: commentData
  })
  
  // 更新帖子评论数
  await artPostsCollection.doc(postId).update({
    data: {
      commentCount: db.command.inc(1)
    }
  })
  
  return {
    success: true,
    message: '评论成功'
  }
}

// 获取评论列表
async function getComments(data) {
  const { postId, page = 1, pageSize = 20 } = data
  const skip = (page - 1) * pageSize
  
  const comments = await commentsCollection
    .where({
      postId
    })
    .orderBy('createTime', 'desc')
    .skip(skip)
    .limit(pageSize)
    .get()
  
  return {
    success: true,
    data: comments.data,
    hasMore: comments.data.length === pageSize
  }
} 